<template>
    <el-dialog v-model="visible" :title="title" :width="width" @closed="resetForm" @open="init" :close-on-press-escape="false">
        <el-form :model="dict" :rules="rules" label-width="94px" label-position="left" label-suffix="：" ref="formRef">
            <el-form-item label="编号" prop="id" style="display: none">
                <el-input v-model="dict.id"/>
            </el-form-item>
            <el-form-item label="所属字典" prop="parentId">
                <el-select v-model="dict.parentId" placeholder="选择父级字典">
                    <el-option :value="item.value" :label="item.label" v-for="(item) in this.$store.state.dictTypes"/>
                </el-select>
            </el-form-item>
            <el-form-item label="字典名称" prop="name">
                <el-input v-model="dict.name" placeholder="请输入字典名称"/>
            </el-form-item>
            <el-form-item label="字典编码" prop="code">
                <el-input v-model="dict.code" placeholder="请输入字典名称"/>
            </el-form-item>
            <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="dict.enabled">
                    <el-radio :label="1">可用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="dict.remark"/>
            </el-form-item>
            <span class="explain">说明：父级字典可不填，不填表示父级字典为全部分类。</span>
        </el-form>
        <template #footer>
            <el-button type="default" @click="visible=false">取消</el-button>
            <template v-if="type===0">
                <el-button type="primary" @click="submitAdd">确认</el-button>
            </template>
            <template v-else>
                <el-button type="primary" @click="submitUpdate">确认</el-button>
            </template>
        </template>
    </el-dialog>
</template>

<script>
    import {ElLoading,ElMessage} from "element-plus";
    import {
        addDict,
        getDictTypes,
        hasSomeSiblingCode,
        hasSomeSiblingDict,
        updateDict
    } from "../../../../network/sys/dict";
    import {getCurrentInstance, reactive, ref, toRefs} from "vue";

    export default {
        name: "DictForm",
        emits:['refresh-data'],
        setup(props,{emit}){
            const visible = ref(false);
            const formRef = ref(null);
            const globalProperties = getCurrentInstance()?.appContext.config.globalProperties;
            const validateDictName = (rule,value,callback)=>{
                hasSomeSiblingDict({
                    id: form.dict.id,
                    name: value,
                    parentId: form.dict.parentId ? form.dict.parentId : 1,//父编号为空即表示为1
                }).then(vo=>{
                    if(vo){
                        callback(new Error('同级目录下存在相同字典'));
                    }
                    callback();
                })
            }
            const validateDictCode = (rule,value,callback)=>{
                if(form.dict.parentId===null){
                    hasSomeSiblingCode({
                        id: formRef.id,
                        code: value,
                    }).then(vo=>{
                        if(vo){
                            callback(new Error('同级目录下已存在相同编码字典'));
                        }
                        callback();
                    })
                }else{
                    callback();
                }
            }
            const form = reactive({
                dict: {
                    id: null,
                    name: null,
                    code: null,
                    parentId: null,
                    enabled: 1,
                    remark: null
                },
                rules: {
                    name: [
                        {required: true, message: '请输字典名称',trigger: 'blur'},
                        {validator: validateDictName,trigger: 'blur'},
                    ],
                    code: [
                        {required: true, message: '请输入字典编码',trigger: 'blur'},
                        {validator: validateDictCode,trigger: 'blur'},
                    ]
                },
                submitAdd: ()=>{
                    formRef.value.validate((valid)=>{
                        if(valid){
                            let loading = ElLoading.service({
                                lock: true,
                                text: '正在添加字典...',
                            })
                            addDict(form.dict).then(vo=>{
                                loading.close();
                                globalProperties.$response.handle({
                                    data: vo,
                                    success: '添加成功',
                                    error:'添加失败',
                                    successFn: ()=>{
                                        emit('refresh-data');//刷新数据表格
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单。')
                        }
                    })
                },
                submitUpdate: ()=>{
                    formRef.value.validate((valid)=>{
                        if(valid){
                            let loading = ElLoading.service({
                                lock: true,
                                text: '正在修改字典...'
                            })
                            updateDict(form.dict).then(vo=>{
                                loading.close();
                                globalProperties.$response.handle({
                                    data:vo,
                                    success: '修改成功',
                                    error: '修改失败',
                                    successFn: ()=>{
                                        emit('refresh-data')
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单。')
                        }})
                },
                setDict: ({id, name, code, parentId, enabled, remark})=>{
                    form.dict.id = id;
                    form.dict.name = name;
                    form.dict.code = code;
                    form.dict.parentId = parentId===1?null:parentId;
                    form.dict.enabled = enabled;
                    form.dict.remark = remark;
                },
                resetForm: ()=>{
                    formRef.value.resetFields();
                    formRef.value.clearValidate();
                    // console.log('重置form.dict',form.dict);
                }
            })

            return{
                ...toRefs(form),
                formRef,
                visible,
            }
        },
        props:{
            width: ''
        },
        data(){
            return{
                type: 0,//0为添加表单，1为修改表单
                title: '',//表单名称
                cascade:[],
                options: [],
                cascadeProps:{}
            }
        },
        methods:{
            loadDictList(){
                if(this.$store.state.dictTypes.length === 0){
                    getDictTypes().then(vo=>{
                        this.$store.commit('setDictTypes',vo.data);
                    })
                }
                // console.log('types',this.$store.state.dictTypes);
            },
            init(){
                this.loadDictList();
            }
        },
        created() {
            this.init();
        }
    }
</script>

<style scoped>
    .el-select-dropdown__item{
        width: 100%;
    }
    .explain{
        font-size: 12px;
        color: #a1a1a1;
    }
</style>
<style>
    .el-cascader-node{
        width: 100%;
    }
    .el-scrollbar__view{
        width: 180px;
    }
</style>
